package repositories

import (
	"gitee.com/golanglearn/small/database"
	"gitee.com/golanglearn/small/models"
)

type TaskRepository interface {
	Create(t *models.Task) error
	FindByTid(tid int) (*models.Task, error)
	FindByExec(Exec string) (*models.Task, error)
}

type taskRepository struct {
	*database.MySQLDB
}

func NewTaskRepository(db *database.MySQLDB) TaskRepository {
	return &taskRepository{db}
}

func (tr *taskRepository) Create(t *models.Task) error {

	stmt, err := tr.DB.Prepare("INSERT INTO task SET t_id=?, exec=?, u_id=?, created_at=?")
	if err != nil {
		return err
	}
	defer stmt.Close()
	result, err := stmt.Exec(t.TID, t.Exec, t.UID, t.CreatedAt.Format("20060102150405"))
	if err != nil {
		return err
	}

	tId, err := result.LastInsertId()
	if err != nil {
		return err
	}
	t.ID = int(tId)

	return nil
}

func (tr *taskRepository) FindByTid(tid int) (*models.Task, error) {
	task := models.Task{}

	err := tr.DB.QueryRow("SELECT u.name executor, t.created_at FROM task t INNER JOIN users u ON t.u_id = u.id WHERE t.t_id = ?", tid).Scan(&task.Executor, &task.CreatedAt)
	if err != nil {
		return nil, err
	}

	return &task, nil
}

func (tr *taskRepository) FindByExec(exec string) (*models.Task, error) {
	task := models.Task{}

	err := tr.DB.QueryRow("SELECT u_id FROM task WHERE exec = ? ORDER BY created_at DESC LIMIT 0,1", exec).Scan(&task.UID)
	if err != nil {
		return nil, err
	}

	return &task, nil
}
